const app = getApp();
const config = require('../../config.js');

let loadOrderListState = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startDate: '',
    endDate: '',
    winHeight: "",
    storage: '',
    pageCount: 10,
    index: 1,
    city: ['全部', '我寄出的', '我收到的'],
    circleH: false,
    spread: false,
    //窗口高度    
    currentTab: 0,
    //预设当前项的值  
    scrollLeft: 0,
    //tab标题的滚动条位置  
    showViewTotal: false,
    showView: true,
    userInfo: null,
    loginUser: null,
    isFromSearch: true,
    // 用于判断searchSongList数组是不是空数组，默认true，空的数组    searchPageNum: 1, // 设置加载的第几次，默认是第一次      
    callbackcount: 10,
    //返回数据的个数    
    searchLoading: false,
    //"上拉加载"的变量，默认false，隐藏    
    searchLoadingComplete: false
    //“没有数据”的变量，默认false，隐藏   
  },

  swichNav: function (e) {
    var cur = e.target.dataset.current;
    // console.info(cur); 
    // console.info(this.data.currentTab);
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur,
        showView: false
      })
    }
  },
  formReset: function () {
    // console.log('form发生了reset事件')
  },
  weiqian: function (e) {
    this.setData({ "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1" });
    this.data.index = 1;
    //原查询方法使用与公
    getOrderList(this);
  },
  yiqian: function (e) {
    this.setData({ "tab_wqs": "nav_1_1", "tab_yqs": "nav_1_1_h" });
    this.data.index = 2;
    //原查询方法使用与公办
    getOrderList(this);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.loginUser == null || app.loginUser.id == null && app.loginUser.mobile == null) {
      wx.navigateTo({
        url: '/pages/authorizedLogin/authorizedLogin'
      })
      return;
    }
    this.setData({ "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1" });

    this.data.startDate = getDate(-7);
    this.data.endDate = getDate();
    this.data.pageCount = 10;
    this.data.index = 1;
    this.setData({ startDate: this.data.startDate, endDate: this.data.endDate });
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    });
  },
  //  点击日期组件确定事件  
  bindDateChageStart: function (e) {
    this.setData({
      startDate: e.detail.value
    });
    this.data.startDate = e.detail.value;
    //原查询方法使用与公办
    getOrderList(this);
  },
  bindDateChangeEnd: function (e) {
    this.setData({
      endDate: e.detail.value
    })
    this.data.endDate = e.detail.value;
    //原查询方法使用与公办
    //getList(this);
    getOrderList(this);
  },


  //扫码
  toScanQRcode() {
    wx.scanCode({
      success: (res) => {

        // 获取扫描条码结果 判断条码信息是否正确
        console.log("扫码结果:" + res.result);
        if (res.result.indexOf(",") == -1) {
          wx.showModal({
            title: '提示',
            content: '抱歉，该运单状态为未受理',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
          return false;
        }

        var values = res.result.split(",");
        var tenantCode = values[0];
        var orderNumber = values[1];

        getBarCodeOrInputNumberOrder(this, "1", orderNumber, tenantCode);
          
      },
      fail: (res) => {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: res,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        })
        return false
      }
    })
  },

  orderNumberInput: function (e) {
    this.setData({
      inputOrderNumberValue: e.detail.value
    })
  },
  //放大镜跳转货物跟踪页
  toFreightTrack: function (e) {
    var orderNumber = this.data.inputOrderNumberValue;
    if (orderNumber == undefined || orderNumber == "") {
      app.tip("运单号不可以为空，请输入运单号", 'none')
    } else {
      // 根据输入订单号 查询订单信息。
      getBarCodeOrInputNumberOrder(this, "2", orderNumber);
    }
  },

  /**
   * 根据订单类型，打开订单详情或编辑页面
   */
  doNavigateToEdit: function (e) {
    var id = e.currentTarget.dataset.id;
    var array = this.data.wuliu;
    var order = array[id];
    if (this.data.index == 1) {
      var urlPath = "";
      if (order.generateFlag == 0){
        urlPath = "orderDetailEdit?order=" + JSON.stringify(order);
      }else{
        urlPath = "orderDetail?order=" + JSON.stringify(order);
      }  
      wx.navigateTo({ url: urlPath});
    } else {
      wx.navigateTo({ url: "orderDetail?order=" + JSON.stringify(order) });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.loginUser == null || app.loginUser.id == null && app.loginUser.mobile == null) {
      wx.navigateTo({
        url: '/pages/authorizedLogin/authorizedLogin'
      })
      return;
    }
    if (this.data.startDate == "") {
      this.data.startDate = getDate();
    }
    if (this.data.endDate == "") {
      this.data.endDate = getDate();
    }
    // 根据加载订单列表状态，查询自动加载订单列表信息。
    if (loadOrderListState == true) {
      getOrderList(this);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.pageCount = 10;
    //原查询方法使用与公办
    //getList(this);
    getOrderList(this);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.pageCount = this.data.pageCount + 10;
    //原查询方法使用与公办
    //getList(this);
    getOrderList(this);
  }
  // ,

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
});
/**
 * 获取当前日期
 */
var getDate = function (num) {
  let tempDate = new Date();
  if (num != undefined && "" != num) {
    tempDate.setDate(tempDate.getDate() + num);//获取AddDayCount天后的日期 
  }
  let nowDate = new Date(Date.parse(tempDate));
  //年  
  let Y = nowDate.getFullYear();
  //月  
  let M = (nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1);
  //日  
  let D = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate();
  return Y + "-" + M + "-" + D;
};

/**
 * 查询数据（定制版）
 */
function getOrderList(_this) {
  findList(_this, function (msg) {
    let result = msg.data.content;
    if (Object.prototype.toString.call(result) === "[object Array]" && result.length > 0) {
      _this.setData({
        wuliu: msg.data.content,
        startDate: _this.data.startDate,
        endDate: _this.data.endDate,
        index: _this.data.index,
        generateFlag: _this.data.index,
        showView: true
      });
    } else {
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "https://7075-public-bb1cff-1257643776.tcb.qcloud.la/noData.png?sign=ce0f461a731ab901f7f26c5ad354c749&t=1570586800",
        index: _this.data.index
      });
    }
  })
}


/**
 * 扫码条形码查询订单数据（定制版）
 * _searchType:[1:扫码，2:文本]
 */
function getBarCodeOrInputNumberOrder(_this, _searchType, _orderNumber, _tenantCode) {
  getBarCodeOrderList(_this, _searchType, _orderNumber, _tenantCode, function (msg) {
    let result = msg.data.content;
    if (Object.prototype.toString.call(result) === "[object Array]" && result.length > 0) {
      _this.setData({
        mobile: app.loginUser.mobile,
        wuliu: msg.data.content,
        startDate: _this.data.startDate,
        endDate: _this.data.endDate,
        index: _this.data.index,
        generateFlag: _this.data.index,
        showView: true
      });
    } else {
      _this.setData({
        showView: false,
        message: "抱歉，没有找到条码相关订单数据！",
        imagePath: "https://7075-public-bb1cff-1257643776.tcb.qcloud.la/noData.png?sign=ce0f461a731ab901f7f26c5ad354c749&t=1570586800",
        index: _this.data.index
      });
    }
  })
}


/**
 * 查询数据
 */
function getList(_this) {
  findList(_this, function (msg) {
    console.log(msg.data.content);
    let result = msg.data.content;
    let arr = new Array();
    if (Object.prototype.toString.call(result) === "[object Array]" && result.length > 0) {
      for (let i = 0; i < result.length; i++) {
        let temp = { dh: result[i].id, receiver: result[i].receiver, unloadPlace: result[i].unloadPlace, companyName: result[i].tenantName, orderCreateTime: result[i].orderCreateTime };
        if (result[i].generateFlag == 0 || result[i].generateFlag == false) {
          temp.generateFlag = 'wqs';
        }
        if (result[i].generateFlag == 1 || result[i].generateFlag == true) {
          temp.generateFlag = 'yqs';
        }
        if (undefined != result[i].orderNumber && "null" != result[i].orderNumber && null != result[i].orderNumber) {
          temp.orderNumber = result[i].orderNumber
        } else {
          temp.orderNumber = "";
        }

        arr.push(temp);
      }
      _this.setData({ companyName: app.companyInfo.name, wuliu: arr, startDate: _this.data.startDate, endDate: _this.data.endDate, index: _this.data.index, showView: true });
    } else {
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "https://7075-public-bb1cff-1257643776.tcb.qcloud.la/noData.png?sign=ce0f461a731ab901f7f26c5ad354c749&t=1570586800",
        index: _this.data.index
      });
    }
  })
}

/**
 * 请求数据
 */
function findList(_this, callback) {
  if (_this.data.startDate > _this.data.endDate) {
    app.tip("开始时间不能晚于结束时间", "none");
    return false;
  }
  wx.showLoading({ mask: true, title: "加载中" });
  let par = {
    orderNumber: _this.data.inputOrderNumberValue,
    startDate: _this.data.startDate,
    endDate: _this.data.endDate,
    userId: app.loginUser.id,
    mobile: app.loginUser.mobile,
    flag: 0,
    currentPage: 1,
    pageSize: _this.data.pageCount,
    code: config.tenantCode
  };

  if (_this.data.index != 0) {
    par.generateFlag = _this.data.index == 1 ? 0 : 1;// 0: 我寄出的 ,  1 : 我收到的
  }

  // console.log(par);
  wx.request({
    url: config.requestUrl + "order/getOrderListPublic",
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
    },
    data: { "data": par },
    success: function (msg) {
      callback(msg);
      wx.hideLoading();
    },
    fail: function (msg) {
      // console.log(msg);
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "https://7075-public-bb1cff-1257643776.tcb.qcloud.la/noData.png?sign=ce0f461a731ab901f7f26c5ad354c749&t=1570586800",
        index: _this.data.index
      });
      wx.hideLoading();
    }
  });

  // 恢复默认orReady方法中的 加载订单列表数据。
  loadOrderListState = true;
}

/**
 * 根据扫描条形码获取订单列表信息
 */
function getBarCodeOrderList(_this, _searchType, _orderNumber, _tenantCode, callback) {
  wx.showLoading({ mask: true, title: "加载中" });
  let par;
  if (_searchType == 1) {
    // 扫码查询条件
    par = {
      orderNumber: _orderNumber,
      tenantCode: _tenantCode,
      userId: app.loginUser.id,
      mobile: app.loginUser.mobile,
      flag: 0,
      currentPage: 1,
      pageSize: _this.data.pageCount,
      code: config.tenantCode
    };
  } else {
    par = {
      orderNumber: _this.data.inputOrderNumberValue,
      startDate: _this.data.startDate,
      endDate: _this.data.endDate,
      userId: app.loginUser.id,
      mobile: app.loginUser.mobile,
      flag: 0,
      currentPage: 1,
      pageSize: _this.data.pageCount,
      code: config.tenantCode
    };
  }

  wx.request({
    url: config.requestUrl + "order/getOrderListPublic",
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
    },
    data: { "data": par },
    success: function (msg) {
      // 获取扫描订单返回订单信息  判断订单是我寄出的 或是 我收到的
      if (msg != null && msg != undefined) {
        var result = msg.data.content;
        if (result != null && result != undefined) {
          var orderObj = (result.length > 0 ? result[0] : null);
          if (orderObj != null) {
            // 设置选中我收到的选项卡
            var senderState = orderObj.senderMobile;
            if (senderState == app.loginUser.mobile) {
              _this.setData({ "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1", "index": 1 });
            }
            var receiverState = orderObj.receiverMobile;
            if (receiverState == app.loginUser.mobile) {
              _this.setData({ "tab_wqs": "nav_1_1", "tab_yqs": "nav_1_1_h", "index": 2 });
            }
          }
        }
      }
      callback(msg);
      wx.hideLoading();
    },
    fail: function (msg) {
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "https://7075-public-bb1cff-1257643776.tcb.qcloud.la/noData.png?sign=ce0f461a731ab901f7f26c5ad354c749&t=1570586800",
        index: _this.data.index
      });
      wx.hideLoading();
    }
  });
  // 控制扫码查询数据后， 不执行orReady方法中的 加载订单列表数据。
  loadOrderListState = false;
}